package com.jieshuibao.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Category;
import com.jieshuibao.model.db.Company;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.Level;
import com.jieshuibao.model.db.UpVersion;
import com.jieshuibao.model.db.UpVersionExample;
import com.jieshuibao.model.db.UpVersionExample.Criteria;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.Version;
import com.jieshuibao.model.domain.ConfigUserResponse;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.DownloadApkResponse;
import com.jieshuibao.model.domain.LoadConfigRequest;
import com.jieshuibao.model.domain.LoadConfigResponse;
import com.jieshuibao.model.domain.LoginRequest;
import com.jieshuibao.model.domain.LoginResponse;
import com.jieshuibao.service.CategoryService;
import com.jieshuibao.service.CompanyService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.CounselorService;
import com.jieshuibao.service.LevelService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UpVersionService;
import com.jieshuibao.service.UserCompanyService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.VersionService;

@Controller
@RequestMapping(value="/load")
public class LoadConfigController {
	private static final Logger logger = LoggerFactory
			.getLogger("LoadConfig.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private CounselorService counselorService;
	@Resource
	private CompanyService companyService;
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	@Resource
	private UserCompanyService userCompanyService;
	@Resource
	private LevelService levelService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private CounselorDutyService counselorDutyService;
	
	@Resource
	private VersionService versionService;
	
	@Resource
	private UpVersionService upVersionService;
	
	@Value("${cert.images.url}")
	private String certImagesUrl;

	@Value("${head.images.url}")
	private String headImagesUrl;
	
	@Value("${question.images.url}")
	private String questionImagesUrl;
	
	@Value("${article.images.url}")
	private String articleImagesUrl;
	
	@Value("${card.images.url}")
	private String cardImagesUrl;
	
	@Value("${rotation.images.url}")
	private String rotationIamgesUrl;
	
	@Value("${drama.cover.url}")
	private String dramaCoverUrl;
	
	@Value("${wish.cover.url}")
	private String wishCoverUrl;
	
	@Value("${version.number}")
	private int version;
	
	@Value("${price.num}")
	private int priceNum;
	
	@Value("${min.money}")
	private double minMoney;
			 
	@Value("${add.money}")
	private int addMoney; 
	
	@Value("${national.money}")
	private double nationalMoney;
	
	@Value("${getsecretly.money}")
	private double secretlyMoney;
	
	@Value("${is.dev}")
	private int isDev;
	
	@Value("${withdraw.money}")
	private double withdrawMoney;

	@Value("${android.version.code}")
	private int androidVersionCode;

	
	@Value("${release.version.code}")
	private int releaseVersion;
	
	
	
	@RequestMapping(value="/config",method = RequestMethod.POST)
	@ResponseBody
	public Object loadConfig(HttpServletRequest request,
			@RequestBody LoadConfigRequest loadConfigRequest){
		LoadConfigResponse loadConfigResponse=new LoadConfigResponse();
		LoginResponse loginResponse = new LoginResponse();
		ConfigUserResponse configUserResponse=new ConfigUserResponse();
		
		try {
			logger.info("接收：" + mapper.writeValueAsString(loadConfigRequest));

			int versionNum = loadConfigRequest.getVersion();
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);
				// String phoneNumber = redisService.get(cookieId);
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					User user = userService.getUserByPhoneNumber(phoneNumber);
					if(user!=null){
						if (user.getSex() == null) {
							loginResponse.setGender("男");
						} else if (user.getSex() == 2) {
							loginResponse.setGender("女");
						} else {
							loginResponse.setGender("男");
						}
						if (user.getBirthdayDate() != null) {
							SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
							String format = dateFormater.format(user.getBirthdayDate());
							
							loginResponse.setBirthday(format);
						}
						String counselorDuty = user.getCounselorDuty();
						if(counselorDuty!=null){
							StringBuilder stringBuilder=new StringBuilder();
							String[] split = counselorDuty.split(",");
							
							for (String id : split) {
								if(id!=null&&!id.equals("")){
									Duty duty = counselorDutyService.getDutyById(id);
									if(duty!=null){
										
										stringBuilder.append(duty.getDutyName()+" ");
									}
								}
								
							}
							user.setCounselorDuty(stringBuilder.toString());
							
						}
						BeanUtils.copyProperties(loginResponse, user);

						Integer companyRole = user.getCompanyRole();
						String counselorUuid = user.getCounselorUuid();
						if (counselorUuid != null) {
							Counselor counselor = counselorService
									.getCounselorByUuid(counselorUuid);
							if (counselor != null) {
								// 申请了咨询师

								Date applyDate = counselor.getApplyDate();
								if (applyDate != null) {
									loginResponse.setApplyTime(applyDate);
								}
								String counselorLevel = counselor
										.getCounselorLevel();

								if (counselorLevel != null
										&& !counselorLevel.equals("")) {
									Level level = levelService
											.getLevelByUuid(counselor
													.getCounselorLevel());
									loginResponse.setLevelName(level.getName());
									loginResponse.setLevelMoney(level.getMoney());
								}

								String adept = counselor.getAdept();
								if (adept != null && !adept.equals("")) {
									String[] adeps = adept.split(",");
									HashMap<String, String> map = new HashMap<String, String>();
									for (String categoyrUuid : adeps) {
										if (categoyrUuid != null) {
											Category categoryById = categoryService
													.getCategoryById(categoyrUuid);
											if (categoryById != null) {
												map.put(categoyrUuid,
														categoryById.getName());
											}

										}

									}
									loginResponse.setAdepts(map);
								}
								BeanUtils.copyProperties(loginResponse, counselor);

							} 
						}
						if (companyRole == 1 || companyRole == 2) {
							// 申请了企业用户
							String companyUuid = user.getCompanyUuid();
							Company company = companyService
									.getCompanyByUuid(companyUuid);
							if (company != null) {
								loginResponse
										.setCompanyStataus(company.getStatus());
								loginResponse.setLicenseImage(company
										.getLicenseImage());
							} 
						}

					
					}
			} 
			} 
			
			configUserResponse.setUsers(loginResponse);
			
			if(versionNum<version){
				loadConfigResponse.setCertImagesUrl(certImagesUrl);
				loadConfigResponse.setHeadImagesUrl(headImagesUrl);
				loadConfigResponse.setQuestionImagesUrl(questionImagesUrl);
				loadConfigResponse.setArticleImagesUrl(articleImagesUrl);
				loadConfigResponse.setCardImagesUrl(cardImagesUrl);
				loadConfigResponse.setRotationIamgesUrl(rotationIamgesUrl);
				loadConfigResponse.setDramaCoverUrl(dramaCoverUrl);
				loadConfigResponse.setWishCoverUrl(wishCoverUrl);
				loadConfigResponse.setVersion(version);
				loadConfigResponse.setPriceNum(priceNum);
				loadConfigResponse.setMinMoney(minMoney);
				loadConfigResponse.setNationalMoney(nationalMoney);
				loadConfigResponse.setAddMoney(addMoney);
				loadConfigResponse.setSecretlyMoney(secretlyMoney);
				loadConfigResponse.setIsDev(isDev);
				loadConfigResponse.setWithdrawMoney(withdrawMoney);
				configUserResponse.setConfig(loadConfigResponse);
				configUserResponse.setCode("1");//需要重新加载配置文件
			}else {
				configUserResponse.setCode("4");//不需要重新加载配置文件
				//configUserResponse.setDes("不需要重新加载配置文件");
			}
			logger.info("返回：" + mapper.writeValueAsString(configUserResponse));

		} catch (Exception e) {
			
			e.printStackTrace();
			configUserResponse.setCode("0");//不需要重新加载配置文件
			configUserResponse.setDes("系统繁忙");
		}
		
		return configUserResponse;
	}
	
	
	//安卓更新版本
	@RequestMapping(value="/versionCode",method = RequestMethod.POST)
	@ResponseBody
	public Object downloadApk(HttpServletRequest request){
		DownloadApkResponse downloadApkResponse = new DownloadApkResponse();
		
		try {
			List<Version> versionCode = versionService.getVersionCode();
			Version version = versionCode.get(0);
			
			downloadApkResponse.setAndroidVersionCode(version.getAndroidCode());
			downloadApkResponse.setCode("1");
			String description = version.getDescription();
			String replace = description.replace("\\n", "\n");
			downloadApkResponse.setDes(replace);
		} catch (Exception e) {
			e.printStackTrace();
			downloadApkResponse.setCode("0");
		}
		return downloadApkResponse;
	}
	//ios更新版本
	@RequestMapping(value="/iosVersion",method = RequestMethod.POST)
	@ResponseBody
	public Object iosReleasVersion(HttpServletRequest request){
		DownloadApkResponse downloadApkResponse = new DownloadApkResponse();
		
		try {
			List<Version> versionCode = versionService.getVersionCode();
			Version version = versionCode.get(0);
			downloadApkResponse.setAndroidVersionCode(version.getIosCode());
			downloadApkResponse.setIosUpCode(version.getIosUpCode());
			downloadApkResponse.setCode("1");
			String description = version.getDescription();
			String replace = description.replace("\\n", "\n");
			downloadApkResponse.setDes(replace);
		} catch (Exception e) {
			e.printStackTrace();
			downloadApkResponse.setCode("0");
		}
		return downloadApkResponse;
	}
	
	@RequestMapping(value="/upversion",method=RequestMethod.POST)
	@ResponseBody
	public Object getUpVersion(HttpServletRequest request,@RequestBody(required=false)LoginRequest req){
		BaseRes<UpVersion> res = new BaseRes<UpVersion>();
		try {
			if (req==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			int deviceType = req.getDeviceType();
			UpVersionExample upVersionExample = new UpVersionExample();
			upVersionExample.setPageIndex(0);
			upVersionExample.setPageSize(1);
			
			Criteria createCriteria = upVersionExample.createCriteria();
			
			if (deviceType==1) {
				createCriteria.andAppTypeEqualTo("1");
			}else if (deviceType==0) {
				createCriteria.andAppTypeEqualTo("0");
			}else {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			
			List<UpVersion> list = upVersionService.getPageUpVersion(upVersionExample);
			if (list!=null&&list.size()>0) {
				UpVersion upVersion = list.get(0);
				res.setData(upVersion);
				res.setCode(BaseRes.SUCCESS_CODE);
				res.setDes(BaseRes.SUCCESS_DES);
				return res;
			}else {
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("未找到版本号！");
				return res;
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}
	}
	
	

	/**
	 * 获取快速问价格、提现最小限额、围观价格、配置金额，钱包余额、财税顾问卡余额、财税问答卡余额
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getconfig/message")
	@ResponseBody
	public Map<String, Object> getQuestionMoney(HttpServletRequest request){
		Map<String, Object> result = new HashMap<String, Object>();
		CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
		User user = userService.getUserByPhoneNumber(cookieUser.getPhoneNumber());
		result.put("questionMoney", minMoney);//快速问价格
		result.put("putForwardMoney", withdrawMoney);//提现最小限额
		result.put("secretlyMoney", priceNum);//围观价格
		result.put("balance", user.getBalance());//钱包余额
		result.put("vipBalance", user.getVipBalance());//财税顾问卡余额
		result.put("QACardBlance", user.getQACardBlance() == null ? BigDecimal.ZERO : user.getQACardBlance());//财税问答卡余额
		result.put("certImagesUrl", certImagesUrl);//证件图片地址
		result.put("headImagesUrl", headImagesUrl);//头像图片地址
		result.put("questionImagesUrl", headImagesUrl);//问题图片地址
		result.put("articleImagesUrl", articleImagesUrl);//文章图片地址
		result.put("cardImagesUrl", cardImagesUrl);//会员卡图片地址
		result.put("rotationIamgesUrl", rotationIamgesUrl);// 轮播图图片地址
		result.put("dramaCoverUrl", dramaCoverUrl);//视频封面图片地址
		result.put("wishCoverUrl", wishCoverUrl);//许愿图片地址
		result.put("nowTime", new Date());//许愿图片地址
		result.put("code", 1);
		return result;
	}
}
